﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XingFuStudio.Pioneer.Net;
using XingFuStudio.Pioneer.Entity;
using FluorineFx.IO;
using XingFuStudio.Pioneer.Applications.City.Config;
using XingFuStudio.Pioneer.Applications.City.Entity;
using XingFuStudio.Pioneer.Applications.City.Element;
using XingFuStudio.Pioneer.Applications.City.Shop;
using XingFuStudio.Pioneer.Applications.City.Config.ConfigKeys;

namespace XingFuStudio.Pioneer.Applications.City.Operation {
    /// <summary>
    /// 货船相关操作
    /// </summary>
    public class Ship : OPBase{
        /// <summary>
        /// 调用方法的目标类
        /// </summary>
        private readonly string Target = "CCityAction.callfunc";

        /// <summary>
        /// 创建业务对象
        /// </summary>
        /// <param name="httpManager"></param>
        /// <param name="account"></param>
        /// <param name="city"></param>
        /// <param name="config"></param>
        public Ship(HttpManager httpManager, AccountInfo account, CityInfo city, UserConfigSection config)
            : base(httpManager, account, city, config) {
        }

         /// <summary>
        /// 重写操作方法
        /// </summary>
        public override void Operate() {
            base.Operate();

            //初始化值为Null
            object value = null;
            //初始化字典是否有值标识
            bool hasValue = false;

            //初始化公共操作对象
            OPCommon opCommon = new OPCommon(this.httpManager, this.account, this.city);

            string message = String.Empty;

            //获取海运产品
            List<ShipShopInfo> items = this.GetTransferItems();
            //获取全部海运船只元素
            var ses = this.city.Elements.Where(s => s is ShipInfo);
            //遍历海船
            foreach (ShipInfo element in ses) {
                try {
                    //判断是否有值，并获取是否自动收获属性值
                    hasValue = config.ConfigItems.TryGetValue(ShipConfigKeys.AutoHarvest, out value);
                    if (hasValue && Convert.ToBoolean(value)) {
                        if (element.GetCanHarvest(items) && this.city.Energy > 0) {
                            bool result = this.HarvestShip(element, out message);
                            //打印日志
                            this.DoPrintLog(true, message);

                            if (result) {
                                element.CanStart = true;
                            }
                        }
                    }

                    //判断是否有值，并获取是否自动收获属性值
                    hasValue = config.ConfigItems.TryGetValue(ShipConfigKeys.AutoStart, out value);
                    if (hasValue && Convert.ToBoolean(value)) {
                        if (element.CanStart) {
                            //判断是否有值，并获取是否自动收获属性值
                            hasValue = config.ConfigItems.TryGetValue(ShipConfigKeys.SellItemId, out value);
                            if (hasValue) {
                                bool result = this.StartShip(element, Convert.ToInt32(value), out message);
                                //打印日志
                                this.DoPrintLog(true, message);
                            }
                        }
                    }
                } catch (Exception ex) {
                    this.DoError(ex);
                }
            }
        }

        public List<ShipShopInfo> GetTransferItems() {
            List<ShipShopInfo> list = new List<ShipShopInfo>();

            //获取全部海运船只元素
            var des = this.city.Elements.Where(s => s is Dock);

            if (des.Count() > 0) {
                Dock dock = (Dock)des.First();

                //获取AMF数据
                AMFMessage message = this.GetAMFMessage("CCityShip.callfunc", "getList", dock.OrderId);

                //解析数据
                Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
                Dictionary<string, object> data = (Dictionary<string, object>)content["data"];

                bool result = ((string)data["result"]) == "succ";

                if (result) {
                    Object[] items = (Object[])data["list"];

                    //遍历数据
                    foreach (Dictionary<string, object> item in items) {
                        //创建商品信息实例对象
                        ShipShopInfo shop = new ShipShopInfo();

                        shop.ID = Convert.ToInt32((string)item["eid"]);
                        shop.Key = (string)item["ekey"];
                        shop.Name = (string)item["ename"];
                        shop.Price = Convert.ToInt32((string)item["price"]);
                        shop.TransTimes = Convert.ToInt32((string)item["transtime"]);
                        shop.FadeTimes = Convert.ToInt32((string)item["fadetime"]);
                        shop.Goods = Convert.ToInt32((string)item["goodsnum"]);
                        shop.Level = Convert.ToInt32((string)item["levellock"]) + 1;

                        //添加到列表
                        list.Add(shop);
                    }
                }

                //返回商品列表
                return list;
            }

            return list;
        }

        /// <summary>
        /// 执行收获船只
        /// </summary>
        /// <param name="cityElemety">操作的元素</param>
        /// <param name="resultMessage">输出参数，用来返回结果信息</param>
        /// <returns></returns>
        public bool HarvestShip(CityElement cityElemety, out string resultMessage) {
            //声明参数字典
            Dictionary<string, object> dicParam = new Dictionary<string, object>();

            List<object> element = new List<object>();
            List<object> lsElement = new List<object>();

            //Element参数字典
            Dictionary<string, object> dicElement = new Dictionary<string, object>();

            //赋值属性
            dicElement.Add("orderid", cityElemety.OrderId);
            dicElement.Add("action", "harvest");
            dicElement.Add("etype", 17);
            //收获相关属性
            Dictionary<string, object> dicHarvest = new Dictionary<string, object>();
            dicHarvest.Add("xp", 2);
            dicHarvest.Add("goods", 16383);
            if (this.city.Energy < this.minEnergy) {
                dicHarvest.Add("energy", 1);
            }
            dicElement.Add("res", dicHarvest);
            //赋值属性
            dicElement.Add("helpflag", false);
            dicElement.Add("toolkey", "");
            dicElement.Add("interval", 5);

            lsElement.Add(dicElement);
            element.Add(lsElement);

            dicParam.Add("element", element);
            dicParam.Add("task", new List<object>());

            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "sync", dicParam);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data1 = (Dictionary<string, object>)content["data"];
            object[] element1 = (object[])data1["element"];
            Dictionary<string, object> result1 = (Dictionary<string, object>)element1[0];

            //获取收获是否成功的状态
            bool result = (string)result1["result"] == "succ";

            //如果成功，获取结果信息
            if (result) {
                //获取执行收获后的同步数据
                Dictionary<string, object> sync = (Dictionary<string, object>)result1["sync"];
                //解析经验，金钱，体力等信息
                int exp = Convert.ToInt32(sync["xp"]);
                int cash = Convert.ToInt32(sync["cash"]);
                int energy = Convert.ToInt32(sync["energy"]);
                int goods = Convert.ToInt32(sync["goods"]);
                //赋值结果字符串
                resultMessage = String.Format("收船成功。 货物:{3}增加:{0} 经验:{4}增加:{1} 剩余体力:{2}",
                    goods - this.city.Goods, exp - this.city.Exp, energy, goods, exp);
                //更新城市信息
                this.UpdateCityInfo(exp, cash, goods, energy);
            } else {
                resultMessage = String.Format("收船失败，{0}！", (string)result1["msg"]);
            }

            return result;
        }

        /// <summary>
        /// 执行开船
        /// </summary>
        /// <param name="cityElemety">操作的元素</param>
        /// <param name="cargoId">货物ID</param>
        /// <param name="resultMessage">输出参数，用来返回结果信息</param>
        /// <returns></returns>
        public bool StartShip(CityElement cityElemety, int cargoId, out string resultMessage) {
            //声明参数字典
            Dictionary<string, object> dicParam = new Dictionary<string, object>();

            List<object> element = new List<object>();
            List<object> lsElement = new List<object>();

            //Element参数字典
            Dictionary<string, object> dicElement = new Dictionary<string, object>();

            //元素相当参数
            Dictionary<string, object> dicExData = new Dictionary<string, object>();
            dicExData.Add("cargoid", cargoId);
            dicElement.Add("exData", dicExData);
            //赋值属性
            dicElement.Add("orderid", cityElemety.OrderId);
            dicElement.Add("action", "setsail");
            dicElement.Add("etype", 17);
            dicElement.Add("interval", 5);

            lsElement.Add(dicElement);
            element.Add(lsElement);

            dicParam.Add("element", element);
            dicParam.Add("task", new List<object>());

            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "sync", dicParam);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data1 = (Dictionary<string, object>)content["data"];
            object[] element1 = (object[])data1["element"];
            Dictionary<string, object> result1 = (Dictionary<string, object>)element1[0];

            //获取收获是否成功的状态
            bool result = (string)result1["result"] == "succ";

            //如果成功，获取结果信息
            if (result) {
                //获取执行收获后的同步数据
                Dictionary<string, object> sync = (Dictionary<string, object>)result1["sync"];
                //解析经验，金钱，体力等信息
                int exp = Convert.ToInt32(sync["xp"]);
                int cash = Convert.ToInt32(sync["cash"]);
                int energy = Convert.ToInt32(sync["energy"]);
                int goods = Convert.ToInt32(sync["goods"]);
                //赋值结果字符串
                resultMessage = String.Format("出航成功。 现金:{3}减少:{0} 经验:{4}增加:{1} 剩余体力:{2}",
                    this.city.Cash - cash, exp - this.city.Exp, energy, cash, exp);
                //更新城市信息
                this.UpdateCityInfo(exp, cash, goods, energy);
            } else {
                resultMessage = String.Format("出航失败，{0}！", (string)result1["msg"]);
            }

            return result;
        }
    }
}
